package android.slc.appbase.utils.process;

import android.slc.app.RbEnterpriseAnalysisApp;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import com.sun.jna.Platform;

import java.util.ArrayList;
import java.util.List;

/**
 * @author slc
 * @date 2024/4/2
 **/
public class ProcessUtils {
    /**
     * 根据当前进程查找系统中进程名相同的进程
     *
     * @return
     */
    public static List<String> findSysProcessByPName() {
        List<String> pIdListByPName = findSysProcessByPName(true);
        return pIdListByPName;
    }

    /**
     * 根据当前进程查找系统中进程名相同的进程
     *
     * @param exceptCurrentProcess 排除当前进程
     * @return
     */
    public static List<String> findSysProcessByPName(boolean exceptCurrentProcess) {
        List<String> pIdListByPName = new ArrayList<>();
        // 获取当前Java进程ID
        String currentPid = String.valueOf(RuntimeUtil.getPid());
        // 获取当前Java进程名称（此处是根据系统的启动文件来的）
        String currentPName = RbEnterpriseAnalysisApp.getCurrentPName();
        // 获取系统中所有Java进程ID
        List<String> javaPIds = RuntimeUtil.execForLines("jps");//此处运行的是当前java程序运行的环境的jps
        //关闭与当前进程同名的其他进程
        for (String pidItem : javaPIds) {
            String[] pidItemPairArray = pidItem.split(StrUtil.SPACE);
            if (ArrayUtil.length(pidItemPairArray) < 2) {
                continue;
            }
            String pidItemId = pidItemPairArray[0];
            String pidItemName = pidItemPairArray[1];
            if (StrUtil.equals(pidItemName, currentPName)) {
                if (exceptCurrentProcess && StrUtil.equals(pidItemId, currentPid)) {
                    continue;
                }
                pIdListByPName.add(pidItemId);
            }
        }
        return pIdListByPName;
    }

    /**
     * 杀死旧的本程序进程名相同的进程
     */
    public static void killOldPidByPName() {
        List<String> pIdListByPName = findSysProcessByPName(true);
        CollectionUtil.forEach(pIdListByPName, new CollUtil.Consumer<>() {
            // 获取当前Java进程ID
            private final String currentPid = String.valueOf(RuntimeUtil.getPid());

            @Override
            public void accept(String value, int index) {
                if (!StrUtil.equals(value, currentPid)) {
                    killProcessByPid(Long.parseLong(value));
                }
            }
        });
    }

    /**
     * 关闭Linux进程
     *
     * @param pid 进程的PID
     */
    public static boolean killProcessByPid(Long pid) {
        if (pid == null || -1 == pid) {
            throw new RuntimeException("Pid ==" + pid);
        }
        boolean result;
        try {
            String killProcessReturns = null;
            if (Platform.isWindows()) {
                killProcessReturns = RuntimeUtil.execForStr("taskkill /F /PID " + pid);
            } else if (Platform.isLinux() || Platform.isAIX()) {
                killProcessReturns = RuntimeUtil.execForStr("kill -9 " + pid);
            }
            Log.get().info("KillProcessReturns：{}", killProcessReturns);
            result = true;
        } catch (Exception e) {
            Log.get().info("杀进程出错：{}", e);
            result = false;
        }
        return result;
    }

}
